package SEG_ApplicationLayer;

import CommonApplicationLayer.InfoComun;
import CommonApplicationLayer.MetodoComun;
import CommonApplicationLayer.SMSComun;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;
import SEG_BusinessLayer.*;
import SEG_EntityLayer.*;
import java.awt.Cursor;
import java.awt.event.KeyEvent;

public class FrmSEG_Login extends JDialog {
    
    //--------------------------------------------------------------------------
    // <editor-fold defaultstate="collapsed" desc="Variables">

        private String sysNombres;

    // </editor-fold>
        
    //--------------------------------------------------------------------------
    // <editor-fold defaultstate="collapsed" desc="Seguridad">
        
        private void obtenerDatosSesion() 
        {
            sysNombres = InfoComun.getInstancia().getNombres();
        }

    // </editor-fold>
        
    //--------------------------------------------------------------------------
    // <editor-fold defaultstate="collapsed" desc="Apariencia">
        
    // </editor-fold>

    //--------------------------------------------------------------------------
    // <editor-fold defaultstate="collapsed" desc="ControlEventos">
        
        public FrmSEG_Login(JFrame parent, boolean modal) {
            super(parent, modal);
            initComponents();
        }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        smsError = new errorProvider.FErrorProvider();
        jPanel1 = new javax.swing.JPanel();
        jSeparator1 = new javax.swing.JSeparator();
        btnCancelar = new boton.FButton();
        btnAceptar = new boton.FButton();
        jSeparator2 = new javax.swing.JSeparator();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        cbxEmpresa = new javax.swing.JComboBox();
        txtUsuario = new javax.swing.JTextField();
        txtPassword = new javax.swing.JPasswordField();

        smsError.setText("fErrorProvider1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Corpec SAC®");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setModal(true);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(239, 246, 253));

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Resources/cancel.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N
        btnCancelar.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        btnCancelar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnCancelar.setMargin(new java.awt.Insets(2, 4, 2, 4));
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        btnAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Resources/accept.png"))); // NOI18N
        btnAceptar.setText("Aceptar");
        btnAceptar.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N
        btnAceptar.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        btnAceptar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnAceptar.setMargin(new java.awt.Insets(2, 4, 2, 4));
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Lucida Fax", 1, 10)); // NOI18N
        jLabel1.setText("Autenticación");

        jLabel2.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N
        jLabel2.setText("Empresa:");

        jLabel3.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N
        jLabel3.setText("Usuario:");

        jLabel4.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N
        jLabel4.setText("Contraseña:");

        cbxEmpresa.setEditable(true);
        cbxEmpresa.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N

        txtUsuario.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N
        txtUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtUsuarioKeyPressed(evt);
            }
        });

        txtPassword.setFont(new java.awt.Font("Lucida Fax", 1, 10)); // NOI18N
        txtPassword.setEchoChar('*');
        txtPassword.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtPasswordKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(btnAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addContainerGap())
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4)
                            .addComponent(jLabel2))
                        .addGap(40, 40, 40)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(cbxEmpresa, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(txtUsuario)
                            .addComponent(txtPassword, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 21, Short.MAX_VALUE))
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jSeparator2)))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(4, 4, 4)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cbxEmpresa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(6, 6, 6))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        setCursor(new Cursor(Cursor.WAIT_CURSOR));
        cargarDatosIniciales();
        setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    }//GEN-LAST:event_formWindowOpened

    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
        if ( esValidoForm() ) {
            setCursor(new Cursor(Cursor.WAIT_CURSOR));
            obtenerDatosUsuario();
            setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        }
    }//GEN-LAST:event_btnAceptarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void txtUsuarioKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtUsuarioKeyPressed
        if ( KeyEvent.VK_ENTER == evt.getKeyCode() ) {
            txtUsuario.transferFocus();
        }
    }//GEN-LAST:event_txtUsuarioKeyPressed

    private void txtPasswordKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPasswordKeyPressed
        if ( KeyEvent.VK_ENTER == evt.getKeyCode() ) {
            txtPassword.transferFocus();
        }
    }//GEN-LAST:event_txtPasswordKeyPressed

    // </editor-fold>
        
    //--------------------------------------------------------------------------
    // <editor-fold defaultstate="collapsed" desc="Funcionalidad">
        
        private void cargarDatosIniciales(){
            listarEmpresas();
            establecerValoresIniciales();
        }
        
        private void establecerValoresIniciales() {
            try {
                cbxEmpresa.setEditable(false);
                AutoCompleteDecorator.decorate(cbxEmpresa);
                txtUsuario.setText(System.getProperty("user.name"));
                txtUsuario.transferFocus();
            } catch( Exception ex ) {
                JOptionPane.showMessageDialog(this, ex.getMessage(), SMSComun.smsEmpresa, JOptionPane.ERROR_MESSAGE);
            }
        }
        
    // </editor-fold>
        
    //--------------------------------------------------------------------------
    // <editor-fold defaultstate="collapsed" desc="AccesoDatos">
        
        private void listarEmpresas() {
            try {
                cbxEmpresa.setModel(new DefaultComboBoxModel( SEG_EmpresaBL.getInstancia().ListarEmpresas().toArray()));
            } catch( Exception ex ){
                JOptionPane.showMessageDialog(this, ex.getMessage(), SMSComun.smsEmpresa, JOptionPane.ERROR_MESSAGE);
            }
        }
        
        private void obtenerDatosUsuario() {
            try {
                byte empresa = ((SEG_EmpresaEL) cbxEmpresa.getSelectedItem()).getEmpresa();
                String login = txtUsuario.getText();
                String clave = String.valueOf(txtPassword.getPassword());
                SEG_UsuarioEL usuario = SEG_UsuarioBL.getInstancia().ObtenerDatosUsuario(login, clave);
                
                if ( usuario != null ) {
                    if ( usuario.isActivo() ) {
                        if ( SEG_UsuarioEmpresaBL.getInstancia().IsUsuarioxEmpresa(empresa, usuario.getUsuario()) ) {
                            InfoComun.getInstancia().setIdEmpresa(empresa);
                            InfoComun.getInstancia().setIdUsuario(usuario.getUsuario());
                            InfoComun.getInstancia().setLogin(usuario.getLogin());
                            InfoComun.getInstancia().setNombres(usuario.getNombres());
                            obtenerDatosSesion();
                            String mensaje = "Bienvenido "+ MetodoComun.getInstancia().getNomPropio(sysNombres) + ".";
                            JOptionPane.showMessageDialog(this, mensaje  , SMSComun.smsEmpresa, JOptionPane.INFORMATION_MESSAGE);
                            dispose();
                        }
                        else {
                            JOptionPane.showMessageDialog(this, SMSComun.smsUsuarioNoEmpresa, SMSComun.smsEmpresa, JOptionPane.WARNING_MESSAGE);
                        }
                    }
                    else {
                        JOptionPane.showMessageDialog(this, SMSComun.smsUsuarioInactivo, SMSComun.smsEmpresa, JOptionPane.WARNING_MESSAGE);
                    }
                }
                else {
                    JOptionPane.showMessageDialog(this, SMSComun.smsErrorUsuario, SMSComun.smsEmpresa, JOptionPane.ERROR_MESSAGE);
                }
            } catch( Exception ex ){
                JOptionPane.showMessageDialog(this, ex.getMessage(), SMSComun.smsEmpresa, JOptionPane.ERROR_MESSAGE);
            }
        }
        
    // </editor-fold>
        
    //--------------------------------------------------------------------------
    // <editor-fold defaultstate="collapsed" desc="Validacion">
        
        private boolean esValidoForm() {
            smsError.setVisible(false);
            if ( cbxEmpresa.getItemCount() == 0 || cbxEmpresa.getSelectedIndex() == -1 ) {
                smsError.setError(cbxEmpresa, SMSComun.smsValorRequerido);
                return false;
            }
            if ( txtUsuario.getText().length() == 0 ){
                smsError.setError(txtUsuario, SMSComun.smsValorRequerido);
                return false;
            }
            if ( txtPassword.getPassword().length == 0 ){
                smsError.setError(txtPassword, SMSComun.smsValorRequerido);
                return false;
            }
            return true;
        }
        
    // </editor-fold>
        
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private boton.FButton btnAceptar;
    private boton.FButton btnCancelar;
    private javax.swing.JComboBox cbxEmpresa;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private errorProvider.FErrorProvider smsError;
    private javax.swing.JPasswordField txtPassword;
    private javax.swing.JTextField txtUsuario;
    // End of variables declaration//GEN-END:variables
}
